<?php

namespace App\Admin\Controllers;

use App\Admin\Models\Notice;
use App\Jobs\SendMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NoticeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $notices = Notice::all();
        return view('admin.notice.index', compact('notices'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.notice.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function store(Request $request)
    {
        // 校验
        $rules = [
            'title' => 'required|string|min:2',
            'content' => 'required|string|min:2',
        ];
        $this->validate($request, $rules);

        // 保存
        /* @var $notice Notice */
        $notice = Notice::query()->create($request->only('title', 'content'));

        // 分发任务
        dispatch(new SendMessage($notice));

        // 渲染
        return redirect('/admin/notices');
    }
}
